import React, { useContext, useEffect, useState } from 'react';
import cs from 'classnames';
import locale from './locale';
import useLocale from '@/utils/useLocale';
import styles from './style/index.module.less';
import {
  Button,
  Form,
  Grid,
  Input,
  Link,
  Modal,
  PaginationProps,
  Select,
  Skeleton,
  Space,
  Spin,
  Table,
  TableColumnProps,
  Typography,
} from '@arco-design/web-react';
import { GlobalContext } from '@/context';
import { AssignedPerson, RefViolations } from '@/api/modules/violation';
import { IconDelete, IconMinus, IconPlus } from '@arco-design/web-react/icon';
import { AssignedPersonItem } from '@/api/interface/violation';
import store from '@/store';
import ActionWrapper from '@/components/ActionWrapper';
import { entityGet } from '@/api/modules/entity';
import clipboard from '@/utils/clipboard';
import Status from '@/components/Status';
import debounce from 'lodash/debounce';
const { useForm } = Form;
const { Row, Col } = Grid;
const Option = Select.Option;
function ViolationLinks({
  links,
  refNumber,
  loading,
  onChange,
  status,
  linkGroup,
}: {
  links: any[];
  refNumber: string;
  loading: boolean;
  onChange: (list: any[]) => void;
  status: any;
  linkGroup: string;
}) {
  const { rtl, lang } = useContext(GlobalContext);
  const t = useLocale(locale);
  const toDetails = (refNumber) => {
    const searchParams = new URLSearchParams(location.search);
    const fromPath = searchParams.get('fromPath');
    const url = `/${
      fromPath == 'task' ? 'MyTasks' : 'Violation'
    }/Detail?fromPath=${fromPath}&refNumber=${refNumber}`;
    window.open(url, '_blank');
  };
  const columns: TableColumnProps[] = [
    {
      title: t['violationLinks.referenceNumber'],
      dataIndex: 'refNumber',
      render: (a, b): JSX.Element => {
        return (
          <Link hoverable={false}>
            <Typography.Text underline onClick={() => toDetails(a)}>
              <Status status={b.status?.key}></Status>
              {a}
            </Typography.Text>
            <Typography.Text
              copyable
              underline
              onClick={() => {
                clipboard(a);
                store.dispatch({
                  type: 'update-referenceDetails',
                  payload: {
                    referenceDetails: { refNumber: a, fullName: b.fullName },
                  },
                });
              }}
            ></Typography.Text>
          </Link>
        );
      },
    },
    {
      title: t['violationLinks.primaryCase'],
      dataIndex: 'primaryCase',
      width: 140,
      render: (a: { value: { [x: string]: any } }): JSX.Element => {
        return <>{a ? t['YES'] : t['NO']}</>;
      },
    },
    {
      title: t['violationLinks.status'],
      dataIndex: 'status',
      width: 200,
      render: (a: { value: { [x: string]: any } }): JSX.Element => {
        return <>{a?.value[lang === 'en-US' ? 'en' : 'ar']}</>;
      },
    },
    {
      title: t['violationLinks.action'],
      dataIndex: 'action',
      width: 200,
      render: (_: any, b: any) => {
        return (
          <>
            {b.primaryCase ? (
              ''
            ) : b.refNumber == primaryCaseRefNumber ? (
              ''
            ) : (
              <ActionWrapper action="violation.detail.addviolationlink">
                <Space size={20}>
                  <Link
                    hoverable={false}
                    status="error"
                    onClick={() => {
                      onDelete(b.refNumber);
                    }}
                  >
                    {/* {t['violationLinks.remove']} */}
                    <IconDelete />
                  </Link>
                </Space>
              </ActionWrapper>
            )}
          </>
        );
      },
    },
  ];
  const [list, setList] = useState<Array<any>>();
  const [primaryCaseRefNumber, setPrimaryCaseRefNumber] = useState('');
  useEffect(() => {
    if (links) {
      setList(links);
      console.log(links);
      const pcRefNumber =
        links.find((a) => !!a.primaryCase)?.refNumber || refNumber;

      setPrimaryCaseRefNumber(pcRefNumber);
    }
  }, [links]);

  useEffect(() => {
    onChange(list);
  }, [list]);

  const onModalChange = (b) => {
    const oldRefNumber = {
      refNumber: primaryCaseRefNumber,
      status: status,
      primaryCase: true,
    };

    const hashExist = list.some((a) => a.refNumber === b.refNumber);

    if (hashExist) {
      onDelete(b.refNumber);
      return;
    }
    const allList = [oldRefNumber, ...list, b];
    const set = new Set(allList.map((item) => item.refNumber));
    const newallList = Array.from(set).map((a) =>
      allList.find((b) => b.refNumber === a)
    );
    setList(() => newallList);
  };

  const onDelete = (refNumber: string) => {
    const newList = list.filter((b) => b.refNumber !== refNumber);
    if (newList.length <= 1) {
      setList([]);
      return;
    }
    setList(() => {
      return newList;
    });
  };

  const [data, setData] = useState([]);
  const [pagination, setPatination] = useState<PaginationProps>({
    sizeCanChange: true,
    showTotal: true,
    pageSize: 10,
    current: 1,
    pageSizeChangeResetCurrent: true,
  });

  const [formParams, setFormParams] = useState({});

  const [visible, setVisible] = useState<boolean>(false);
  const [modalLoading, setModalLoading] = useState<boolean>(false);

  const [assignedPerson, setAssignedPerson] = useState<
    Array<AssignedPersonItem>
  >([]);
  const getAssignedPerson = () => {
    AssignedPerson({})
      .then((res) => {
        setAssignedPerson(res.data);
      })
      .catch((e) => {
        console.log(e);
      });
  };
  const [entitys, setEntitys] = useState([]);
  const getEntitys = () => {
    entityGet({ active: true })
      .then((res) => {
        setEntitys(() => [...res.data]);
      })
      .catch((e) => {
        console.log(e);
      });
  };
  useEffect(() => {
    if (visible) {
      getAssignedPerson();
      getEntitys();
    }
    form.resetFields();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [visible]);
  useEffect(() => {
    if (visible) {
      onSearch();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [
    pagination.current,
    pagination.pageSize,
    JSON.stringify(formParams),
    visible,
  ]);

  const ModalColumns: TableColumnProps[] = [
    {
      title: t['violationLinks.referenceNumber'],
      dataIndex: 'refNumber',
      render: (a, b): JSX.Element => {
        return (
          <Link hoverable={false}>
            <Status status={b.status?.key}></Status>
            <Typography.Text underline onClick={() => toDetails(a)}>
              {a}
            </Typography.Text>
            <Typography.Text
              underline
              copyable
              onClick={() => {
                clipboard(a);
                store.dispatch({
                  type: 'update-referenceDetails',
                  payload: {
                    referenceDetails: { refNumber: a, fullName: b.fullName },
                  },
                });
              }}
            ></Typography.Text>
          </Link>
        );
      },
    },
    {
      title: t['violationLinks.status'],
      dataIndex: 'status',
      render: (a: { value: { [x: string]: any } }): JSX.Element => {
        return <>{a?.value[lang === 'en-US' ? 'en' : 'ar']}</>;
      },
    },
    {
      title: t['violationLinks.action'],
      dataIndex: 'action',
      width: 100,
      render: (_, b): JSX.Element => {
        return (
          <>
            {/* 相等主案件 */}
            {b.refNumber == primaryCaseRefNumber ? (
              ''
            ) : // 选中案件可删
            list.some((a) => a.refNumber === b.refNumber) ? (
              <Link
                hoverable={false}
                status="error"
                className={styles['violationLinks-button']}
                onClick={() => onModalChange(b)}
              >
                <IconMinus />
              </Link>
            ) : // 可以添加的案件,一是没有linkGroup，二是linkGroup和当前linkGroup相等的
            !b.linkGroup || b.linkGroup == linkGroup ? (
              <Link
                hoverable={false}
                className={styles['violationLinks-button']}
                onClick={() => onModalChange(b)}
              >
                <IconPlus />
              </Link>
            ) : (
              ''
            )}
          </>
        );
      },
    },
  ];

  const handleSubmit = debounce(() => {
    const values = form.getFieldsValue();
    setFormParams(values);
    setPatination({
      ...pagination,
      current: 1,
    });
  }, 300);

  const onSearch = () => {
    const { current, pageSize } = pagination;
    setModalLoading(true);
    RefViolations({
      pageNo: current,
      pageSize,
      // refNumber: refNumber,
      ...formParams,
    })
      .then((res) => {
        setData(res.data.data);
        setPatination({
          ...pagination,
          current,
          pageSize,
          total: res.data.count,
        });
        setModalLoading(false);
      })
      .catch(() => {
        setModalLoading(false);
      });
  };

  function onChangeTable({ current, pageSize }) {
    setPatination({
      ...pagination,
      current,
      pageSize,
    });
  }
  const [form] = useForm();

  return (
    <div className={cs(styles['block'], rtl ? 'rtl' : '')}>
      <div className={styles['block-title']}>
        {t['violationLinks.violationLinks']}
      </div>
      <Skeleton loading={loading} text={{ width: '100%', rows: 7 }} animation>
        <div className={cs(styles['button-group'], rtl ? 'rtl' : '')}>
          <Space>
            <ActionWrapper action="violation.detail.addviolationlink">
              <Button
                type="primary"
                icon={<IconPlus />}
                onClick={() => {
                  setVisible(true);
                }}
              >
                {t['violationLinks.add']}
              </Button>
            </ActionWrapper>
          </Space>
        </div>
        <Table
          border={{
            wrapper: true,
            cell: true,
          }}
          scroll={{
            y: 246,
          }}
          columns={columns}
          data={list}
          rowKey="refNumber"
          pagination={false}
          rowClassName={(a) => {
            return a?.status?.key;
          }}
        />
        <div className={styles['space']}></div>
      </Skeleton>

      <Modal
        style={{ width: '860px' }}
        visible={visible}
        maskClosable={false}
        unmountOnExit={true}
        onCancel={() => setVisible(false)}
        footer={null}
        className={rtl ? 'rtl' : ''}
      >
        <Spin
          loading={modalLoading}
          className={cs(styles['spin'], rtl ? 'rtl' : '')}
        >
          <Form
            form={form}
            className={rtl ? styles['search-formrtl'] : styles['search-form']}
            labelAlign="right"
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            onValuesChange={handleSubmit}
          >
            <Row gutter={24}>
              <Col span={12}>
                <Form.Item label={t['violationLinks.search.q']} field="q">
                  <Input
                    style={{ width: '260px' }}
                    allowClear
                    autoComplete="off"
                    placeholder={t['violationLinks.search.q.placeholder']}
                  />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label={t['violationLinks.search.assignedPerson']}
                  field="assignedPerson"
                >
                  <Select
                    style={{ width: '260px' }}
                    allowClear
                    showSearch
                    placeholder={
                      t['violationLinks.search.assignedPerson.placeholder']
                    }
                    filterOption={(inputValue, option) =>
                      option.props.children
                        .toLowerCase()
                        .indexOf(inputValue.toLowerCase()) >= 0
                    }
                  >
                    {assignedPerson.map((option, index) => (
                      <Option key={index} value={option.id}>
                        {`${option.name}(${option.count})`}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label={t['violationLinks.search.name']}
                  field="entityId"
                >
                  <Select
                    style={{ width: '260px' }}
                    allowClear
                    showSearch
                    placeholder={t['violationLinks.search.name.placeholder']}
                    filterOption={(inputValue, option) =>
                      option.props.children
                        .toLowerCase()
                        .indexOf(inputValue.toLowerCase()) >= 0
                    }
                  >
                    {entitys.map((option, index) => (
                      <Option key={index} value={option?.id}>
                        {option[lang === 'en-US' ? 'name' : 'nameAr']}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
            </Row>

            {/* <Button
              type="primary"
              icon={<IconSearch />}
              onClick={() => {
                handleSubmit();
              }}
            >
              {t['violationLinks.search']}
            </Button> */}
          </Form>
          <Table
            border={{
              wrapper: true,
              cell: true,
            }}
            scroll={{
              y: '55vh',
            }}
            columns={ModalColumns}
            data={data}
            pagination={pagination}
            onChange={onChangeTable}
            rowKey="refNumber"
            rowClassName={(a) => {
              return a?.status?.key;
            }}
          ></Table>
        </Spin>
      </Modal>
    </div>
  );
}

export default ViolationLinks;
